import json
import os

import numpy as np
import matplotlib.pyplot as plt
import openpyxl

def set_condition_format():
    import openpyxl
    from openpyxl.styles import Border, Side,PatternFill
    from openpyxl.formatting.rule import FormulaRule,ColorScaleRule

    file_name = "C:/Users/Dell/Documents/PythonFiles/forTESTonly/2sel/base/changeDB1123.xlsx"
    wb = openpyxl.load_workbook(file_name)
    for ws in wb:
        light_pink_fill = PatternFill(start_color='FFFF9B99', end_color='FFFF9B99', fill_type='solid')
        # light_blue_fill = PatternFill(start_color='FF0066FF', end_color='FF0066FF', fill_type='solid')
        # border = Border(right=Side(color='FF000000', border_style="thick"))
        # ws.conditional_formatting.add('$B$2:$B$13', FormulaRule(formula=['A1="test"'], fill=light_pink_fill))
        # ws.conditional_formatting.add('$B$2:$B$13', FormulaRule(formula=['=MAX(B2:B13)'], fill=light_pink_fill))
        for c in range(20):     # 一共有21列，其中，第一列不比较
            BT = chr(ord("B") + c)
            if "small" in ws[f"{BT}1"]:
                ws.conditional_formatting.add(f'{BT}2:{BT}13',
                                              ColorScaleRule(start_type='max', start_color='004311',
                                                             end_type='min', end_color='ffaca3'))
            else:
                ws.conditional_formatting.add(f'{BT}2:{BT}13',
                                              ColorScaleRule(start_type='min', start_color='004311',
                                                             end_type='max', end_color='ffaca3'))













# print('A',ord("A"),chr(ord("A")))

def find_no_in(data,prime_num,base_path,n,m):
    # 应该是要找到一个模型的优势数据集的图片编号，是原来数据集的子集
    # 写入一个json文件，优势指标名，综合的优势图片名
    metrics = ['sen', 'me', 'mse(small)', 'avg', 'std', 'vifp', 'snr', 'min', 'uqi', 'qabf', 'vif', 'ssim', 'psnr',
               'ifc', 'q0i', 'ce(small)', 'edge', 'qcv(small)', 'sf', 'qcb']
    prime = {}
    for model, pic in data.items():
        prn = prime_num[model]      # 获取每个指标的优势图片数
        prn_no = np.argsort(prn)       # 找到靠前的指标
        # print(prn_no)
        prn_no = list(reversed(prn_no))

        p = prn_no[:5]     # 找5个靠前的指标
        p_name = list(map(lambda x:metrics[x],p))
        p_115_num = [sum(pic[i][j] for j in p)  for i in range(115)]  # 找这5个指标的图片数

        # for i in range(115):
        #     p_115_num = sum([pic[i][j] for j in p])
        p_115_no = list(reversed(np.argsort(p_115_num)))        # 将图片数从大到小排序，得到优势图片索引

        # 获取多于4个的值
        i = 0
        while p_115_num[p_115_no[i]] >= 4: i+=1

        # 将图片索引从1开始
        xls_p_115_no = list(map(lambda x:x+1,p_115_no))
        xls_p_115_no = list(map(int, xls_p_115_no))

        prime[model]= {"metrics":p_name,"pics":xls_p_115_no[:i]}     # 保存模型信息

    with open(base_path + "prime_pics.json", "w", encoding="utf8") as f:
        f.write(json.dumps(prime))


def find_pic_no():
    """运行该函数，查看一个模型的优势图片
    返回一个模型的优势指标和优势图片的号码
    """

    # 获取要找的模型，result

    base_path = "C:/Users/Dell/Documents/PythonFiles/forTESTonly/2sel/base/"
    with open(base_path + "result.json", "r", encoding="utf8") as f:
        data = json.loads(f.read())
    # print(','.join(map(repr,map(lambda x:x[:-5],data.keys()))))  #用于获取已经测试过的01数据文件名
    # print(list(map(lambda x:x[:-5],data.keys())))  #用于获取已经测试过的01数据文件名
    #
    with open(base_path + "prime_num.json", "r", encoding="utf8") as f:
        prime_num = json.loads(f.read())

    # 暂定从7个最佳指标中选出5个
    find_no_in(data,prime_num,base_path,7,5)

# find_pic_no()
#
# print("ok")

def paint3():
    """展示： 让模型名x的优势图片y，对应一个绿点出现
    改进2：设置带网格线
    """
    base_path = "C:/Users/Dell/Documents/PythonFiles/forTESTonly/2sel/base/"
    with open(base_path+"result.json","r",encoding="utf8") as f:
        data = json.loads(f.read())

        x = [[i for i in range(20)]for j in range(115)]
        for i,(model,pic) in zip(range(len(data)),data.items()):
            if i % 5 == 0:
                plt.figure(figsize=(80, 50))
                fig, axs = plt.subplots(nrows=1, ncols=5, figsize=(15, 50))

            ax = axs[i%5]
            ax.set_title(model)
            ax.set_xticklabels(np.arange(0, 20,5),rotation=-60)
            ax.set_yticklabels(np.arange(0, 115),rotation=-60)
            ax.grid("on")
            ax.scatter(x,pic, color='green',marker = 's', s = 3)

            if i % 5 == 4 or i == len(data) -1:
                plt.savefig(f'{base_path}带网格第{i // 5 + 1}张图.png')
                # plt.show()
# paint3()
# print("OK")

def paint2():
    """这个可以直接运行，调试效果更好
    改进:在一张图上展示多张子图
    保存下来！
    """
    base_path = "C:/Users/Dell/Documents/PythonFiles/forTESTonly/2sel/base/"
    with open(base_path+"result.json","r",encoding="utf8") as f:
        data = json.loads(f.read())
        for i,(model,pic) in zip(range(len(data)),data.items()):
            if i % 5 == 0:
                plt.figure(figsize=(110, 50))
                fig, axs = plt.subplots(nrows=1, ncols=5, figsize=(20, 50))

            ax = axs[i%5]
            ax.set_title(model)
            ax.imshow(pic, cmap='Greens')
            if i % 5 == 4 or i == len(data) -1:
                plt.savefig(f'{base_path}第{i // 5 + 1}张图.png')
                plt.show()
                # input()
# paint2()
# print("OK")

def paint():
    """这个目前只能在命令行进行展示:
    目的是，让模型名x的优势图片y，对应一个绿点出现

    """
    import matplotlib.pyplot as plt

    with open("C:/Users/Dell/Documents/PythonFiles/forTESTonly/2sel/base/result.json","r",encoding="utf8") as f:
        data = json.loads(f.read())
        for model,pic in data.items():
            plt.imshow(pic,cmap='Greens')
            input()

# paint()



def len_test():
    print(len([]))

    print(len("fused_rfnnest_700_wir_6.0_wvi_3.0_"))


def in_test():
    print("sm" in "small")
    print("ma" in "small")
    print("ll" in "small")
    print("la" in "small")
    # True
    # True
    # True
    # False


# 测试一下os.path
# import os
# path = "D:/fusion_imgs/source/IR/1.png"
# print(os.path.split(path))
# print(os.path.splitext(path))
# print(path.split("/"))

# ('D:/fusion_imgs/source/IR', '')
# ('D:/fusion_imgs/source/IR/', '')
# ['D:', 'fusion_imgs', 'source', 'IR', '']


# gen_demo()
# print("   ---   ".strip())

def gen_folder():
    '''为保存模型图片生成文件夹'''
    # path = "D:/1126起备份服务器模型"
    # path = "D:/1202第三批备份"
    path = "D:/1213第五批备份"
    # path = "F:/1203/1213第五批备份"

    for i in range(90,116):
        os.mkdir(path+"/"+str(i))

# gen_folder()
# print("OK")




def getfile_name():
    import os, shutil

    dir = "D:/ForFullSavedModel/Use7GModels/1203/compare_results"
    filenames = os.listdir(dir)

    f = list(map(repr, filenames))  # 这是为了将数字转为串,这两句适合MATLAB列表里的值
    print(','.join(f))

    f = list(map(str, filenames))  # 这是为了将数字转为串，存放与xlsx中
    print('\n'.join(f))

    # # 下面这个是为了生成xlsx公式
    xlsx_format = list(map(lambda x: f"='[mytestG7_2.xlsx]{x}'!$117:$117", f))
    print('\n'.join(xlsx_format))

# getfile_name()
#
# print("ok!")

# 一次性的生成一个cell最大值的公式
def genxlsxformule():
    import os, shutil

    dir = "D:/fusion_imgs2/result_img115"
    filenames = os.listdir(dir)

    s = "=MAX("+",".join(map(lambda name:name+"!A2",filenames))+")"

    print(s)

    # =MAX(
    #     DIDFuse!A2, dualbranch_add!A2, dualbranch_channel!A2, dualbranch_l1!A2, FGAN!A2, nest_attention_avg!A2, nest_attention_max!A2, nest_attention_nuclear!A2, PerGAN!A2, rfn_nest_source!A2, D2WGan!A2, GANMcC!A2,



# genxlsxformule()
#
# print("ok!")


def gen_jsonfile():
    "再生成一下json文件名"
    import os

    # dir = "D:/ForFullSavedModel/Use7GModels/1117/compare_results"
    dir = "D:/ForFullSavedModel/Use7GModels/1203/compare_results"
    filenames = os.listdir(dir)

    path = "myresults/"
    f = list(map(str, filenames))  # 这是为了将数字转为串，存放与xlsx中
    for f_name in f:
        with open(path + f_name + ".json", "w", encoding="utf8") as newfile:
            pass


# gen_jsonfile()
#
# print("ok!")



def gen_wb_ws():
    # 这个应该就是根据prime_pics.json,读出待选模型的优势照片，然后
    import json
    import openpyxl
    # 用于将进行抽取的模型名建立sheet
    base_path = "2selCELL/"
    with open(base_path + "prime_pics.json", "r", encoding="utf8") as f:
        data = json.loads(f.read())

    new_wb = openpyxl.Workbook()


    # 根据自己的较好的模型的模型名,进行操作
    for name in data.keys():
        new_wb.create_sheet(title=name)
    new_wb.save(base_path+"result.xlsx")
gen_wb_ws()
# print("OK")


# 此函数输入一个result.xlsx路径,打印前三的排名数
def sum_fn(models):
    for k,v in models.items():
        for i in range(1,len(v)):
            v[i] = v[i] + v[i-1]
        print(k, end='\t')
        print(*v, sep='\t')

def show_result_rank(path):
    wb = openpyxl.load_workbook(path)

    models = {}
    
    for ws in wb:
        name = ws[f"A{ws.max_row}"].value
        models[name] = [0,0,0]        
        for c in range(20):  # 一共有21列，其中，第一列不比较
            temp_data = []
            BT = chr(ord("B") + c)
            value = ws[f"{BT}{ws.max_row}"].value


            # 从B列开始
            for row_index in range(2,ws.max_row+1):     # 添加当前列数据           
                temp_data.append(ws[f"{BT}{row_index}"].value)
            if "small" in ws[f"{BT}1"].value:
                temp_data.sort()
            else:
                temp_data.sort(reverse=True)
            for i in range(3):
                if value is temp_data[i]:
                    models[name][i] += 1

    print(models)
    sum_fn(models)

# path = r"D:\matlab_work\fusion_metrix_results\1217使用逐测cell比较排名\10nn\forTESTonly\2selCELL\result.xlsx"
# path = r"D:\matlab_work\fusion_metrix_results\1217使用逐测cell比较排名\7nn\forTESTonly\2selCELL\result.xlsx"
# path = r"D:\matlab_work\fusion_metrix_results\1217使用逐测cell比较排名\27\forTESTonly\2selCELL\result.xlsx"
# path = r"D:\matlab_work\fusion_metrix_results\1217使用逐测cell比较排名\29\forTESTonly\2selCELL\result.xlsx"
path = r"D:\matlab_work\fusion_metrix_results\1217使用逐测cell比较排名\对101和109数据集缩小至30\forTESTonly\2selCELL\result.xlsx"

# show_result_rank(path)
# print("ok")


# 这个是为MATLAB 生成图标线段等的组合
def get_MATLAB_line_sytle():
    shape_name = ["五角星","上三角","方格","X","+"]
    shape_symb = ["p","^","s","X","+","x","+"]

    color_name= ["红","棕","黑","绿","蓝"]
    color_symb = ["r","m","k","g","b"]

    d = {color+name:repr("-"+ssymb+csymb) for color,csymb in zip(color_name,color_symb) for name,ssymb in zip(shape_name,shape_symb)}


    row_num = len(color_name)
    name,symb = [],[]
    for i,(key,value) in enumerate(d.items()):
        name.append(key)
        symb.append(value)
        if i and not (i+1)%row_num:
            print("\t".join(name))
            print("\t".join(symb))
            print()
            name,symb = [],[]












